package com.springboot.config.security.admin;

import com.springboot.config.security.JwtAuthorizationEntryPoint;
import com.springboot.handler.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/***
 *@descrition: spring-security配置类
 *@author: lzh
 */

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(100)
public class AdminSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AdministratorDetailsService administratorDetailsService;

    @Autowired
    JwtAuthorizationEntryPoint jwtAuthorizationEntryPoint;

    @Autowired
    MyAccessDeniedHandler adminAccessDeniedHandler;

    @Autowired
    AdminAuthenticationTokenFilter adminAuthenticationTokenFilter;

    @Override
    @Bean(BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(administratorDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //关闭session管理
        http.csrf().disable().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().httpBasic().authenticationEntryPoint(jwtAuthorizationEntryPoint)
                .and().exceptionHandling().accessDeniedHandler(adminAccessDeniedHandler)
                .and().authorizeRequests().antMatchers("/admin/login").permitAll()
                ;
        http.addFilterBefore(adminAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);


    }

}
